<template>
  <backContainer>
    <div class="flexBet">
      <!-- tab -->
      <card :width="272" :top="24" height="280px" class="types">
        <div class="topline">全部分类</div>
        <div class="list">
          <div
            class="temp"
            :class="{ active: navtab == item.navtab }"
            @click="changeType(item)"
            v-for="(item, index) in types"
            :key="index"
          >
            <img
              v-if="navtab == item.navtab"
              class="icon"
              :src="item.activeimg"
              alt="加载失败"
            />
            <img v-else class="icon" :src="item.img" alt="加载失败"/>
            <div>{{ item.name }}</div>
            <div class="tag" v-if="courseTypeUnRead > 0 && index == 0">
              {{ courseTypeUnRead > 99 ? '99+' : courseTypeUnRead }}
            </div>
            <div class="tag" v-if="selfTypeUnRead > 0 && index == 1">
              {{ selfTypeUnRead > 99 ? '99+' : selfTypeUnRead }}
            </div>
            <div class="tag" v-if="noticeTypeUnRead > 0 && index == 2">
              {{ noticeTypeUnRead > 99 ? '99+' : noticeTypeUnRead }}
            </div>
          </div>
        </div>
      </card>
      <!-- 消息列表 -->
      <card :width="912" :top="24">
        <!-- 消息 -->
        <div class="message">
          <!-- 标题 -->
          <div class="flexBet" style="border-bottom: 1px solid #edeff0">
            <div class="topline">
              {{ unread }}条待办
              <!-- <img
                @click="clearUnread"
                class="clear_all_icon"
                src="@/assets/images/clear_all_icon.png"
                alt="加载失败"
              /> -->
            </div>
            <div>
              <el-cascader
                :show-all-levels="false"
                style="width: 160px; margin: 24px 10px 0 0"
                size="mini"
                v-if="navtab == 1"
                v-model="keys.indexId"
                placeholder="请选择内容"
                :options="courseIndexTree"
                @change="intoStorge"
                value="id"
                label="name"
                filterable
                clearable
                :props="{
                  expandTrigger: 'hover',
                  checkStrictly: true,
                  value: 'id',
                  label: 'name',
                }"
              >
              </el-cascader>
              <el-select
                v-if="navtab == 1"
                @change="intoStorge"
                style="width: 160px; margin: 24px 10px 0 0"
                v-model="keys.msgType"
                placeholder="请选择类型"
                clearable
                filterable
                size="mini"
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.msgType"
                  :label="item.typeName"
                  :value="item.msgType"
                />
              </el-select>
              <el-select
                v-if="navtab == 2"
                @change="intoStorge"
                style="width: 160px; margin: 24px 10px 0 0"
                v-model="keys.msgType"
                placeholder="请选择类型"
                clearable
                filterable
                size="mini"
              >
                <el-option
                  v-for="item in selfTypeList"
                  :key="item.msgType"
                  :label="item.typeName"
                  :value="item.msgType"
                />
              </el-select>
              <el-select
                v-if="navtab == 3"
                @change="intoStorge"
                style="width: 160px; margin: 24px 10px 0 0"
                v-model="keys.msgType"
                placeholder="请选择类型"
                clearable
                filterable
                size="mini"
              >
                <el-option
                  v-for="item in noticeTypeList"
                  :key="item.msgType"
                  :label="item.typeName"
                  :value="item.msgType"
                />
              </el-select>
              <el-select
                @change="intoStorge"
                size="mini"
                v-model="keys.msgStatus"
                style="width: 100px; margin: 24px 10px 0 0"
                placeholder="请选择状态"
              >
                <el-option label="全部" value=""></el-option>
                <el-option label="未读" :value="0"></el-option>
                <el-option label="已读" :value="1"></el-option>
              </el-select>
              <el-select
                @change="intoStorge"
                size="mini"
                v-model="keys.sortType"
                style="width: 100px; margin: 24px 10px 0 0"
                placeholder="时间排序"
              >
                <el-option label="倒序" value="0"></el-option>
                <el-option label="正序" value="1"></el-option>
              </el-select>
            </div>
          </div>
          <!-- 消息列表 -->
          <div
            v-loading="loading"
            style="
              padding: 8px 40px 0 64px;
              height: calc(100vh - 68px - 18px - 30px - 74px - 10px);
              overflow: auto;
            "
          >
            <!-- 不是通知的消息 -->
            <div
              v-if="msgList.length > 0 && navtab !== 3"
              @click="routeTo(item, index)"
              class="msg_item"
              v-for="(item, index) in msgList"
              :key="index"
            >
              <div class="msg_icon">
                <div v-if="item.readStatus == 0" class="redtip"></div>
                <img src="@/assets/images/classify/msgtype6.png" alt="加载失败"/>
              </div>
              <div class="msgInfo">
                <div class="flex_bt">
                  <div class="msgName">
                    <span v-html="item.title"></span>
                  </div>

                  <div class="create_time">
                    {{ parseTime(item.createTime) }}
                  </div>
                </div>
                <div class="msgDetail flexBet">
                  <span>{{ item.content ? item.content : '暂无内容' }}</span>
                  <div v-if="item.msgType == 7">
                    <el-button
                      type="primary"
                      size="small"
                      v-if="item.markStatus === 1"
                      @click="
                        answerQuestion(item.keyId, item.markStatus, item, index)
                      "
                    >去查看
                    </el-button
                    >
                    <el-button
                      type="primary"
                      size="small"
                      v-if="item.markStatus === 0"
                      @click="
                        answerQuestion(item.keyId, item.markStatus, item, index)
                      "
                    >去填写
                    </el-button
                    >
                  </div>
                </div>
              </div>
            </div>
            <!-- 是通知 -->
            <el-collapse v-if="msgList.length > 0 && navtab == 3">
              <el-collapse-item
                @click.stop.native="clickCollapse(item, index)"
                :name="item.noticeId"
                v-for="(item, index) in msgList"
                :key="index"
              >
                <template slot="title">
                  <div class="flex t rela">
                    <div class="flex">
                      <!-- 图标 -->
                      <div class="msg_icon">
                        <div v-if="item.readStatus == 0" class="redtip"></div>
                        <img
                          v-if="item.noticeClass == 1"
                          src="@/assets/images/classify/system.png"
                          alt="加载失败"
                        />
                        <img
                          v-if="item.noticeClass == 2"
                          src="@/assets/images/classify/school.png"
                          alt="加载失败"
                        />
                      </div>
                      <div class="flexBet msgcontent">
                        <!-- 标题 -->
                        <div>
                          <div class="msgName overTxt">
                            {{
                              item.noticeClass == 1 ? '系统通知' : '学校通知'
                            }}
                          </div>
                          <div class="t_t overTxt">
                            {{ item.noticeTitle || item.title }}
                          </div>
                        </div>
                        <!-- 时间 -->
                        <div class="t_time">
                          {{ parseTime(item.createTime) }}
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
                <div
                  @click="answerQuestion(item.keyId, item.markStatus, index)"
                  :class="[
                    't_content',
                    item.noticeClass == 3 ? 't_content_questionnaires' : '',
                    item.noticeClass == 3 ? 'shou' : '',
                  ]"
                  v-html="item.noticeContent || item.content"
                ></div>
                <div
                  v-if="item.noticeFiles && item.noticeFiles.length > 0"
                  style="margin: 10px 0 0 10px; font-weight: 600; color: black"
                >
                  附件：
                </div>
                <div
                  style="padding: 0 10px"
                  v-for="(fileitem, fileindex) in item.noticeFiles"
                  :key="fileindex"
                >
                  <el-link @click="openfile(fileitem)" type="primary">
                    {{ fileitem.name }}
                  </el-link>
                </div>
              </el-collapse-item>
            </el-collapse>
            <div v-if="msgList.length == 0">
              <el-empty
                style="margin-top: 90px"
                description="暂无事项~"
              ></el-empty>
            </div>
          </div>
        </div>
      </card>
    </div>
  </backContainer>
</template>
<script>
import { getMyMessageList, myMessageCourseList } from '@/api/home/message'
import { changeReadStatus } from '@/api/notificationCenter/notification'
import { updatePost_readmessage } from '@/api/home/message'

export default {
  components: {},
  data() {
    return {
      courseTypeUnRead: 0,
      selfTypeUnRead: 0,
      noticeTypeUnRead: 0,
      keyId: '',
      index: '',
      readStatus: '',
      msgId: '',
      loading: false,
      types: [
        {
          activeimg: require('@/assets/images/classify/classifyActive2.png'),
          img: require('@/assets/images/classify/classify2.png'),
          name: '课程消息',
          navtab: 1
        },
        {
          activeimg: require('@/assets/images/classify/classifyActive4.png'),
          img: require('@/assets/images/classify/classify4.png'),
          name: '个人消息',
          navtab: 2
        },
        {
          activeimg: require('@/assets/images/classify/classifyActive1.png'),
          img: require('@/assets/images/classify/classify1.png'),
          name: '通知消息',
          navtab: 3
        }
      ],
      navtab: 1,
      unread: 0,
      keys: {
        msgStatus: 0,
        sortType: '0',
        indexId: '',
        msgType: ''
      },
      // 消息列表组件参数
      courseIndexTree: [],
      typeList: [
        {
          typeName: '全部消息类型',
          msgType: ''
        },
        //8 9 10为msgType _1为考核 _6为作业
        {
          typeName: '考核互评消息',
          msgType: '8_1'
        },
        {
          typeName: '作业互评消息',
          msgType: '8_6'
        },
        {
          typeName: '考核自评消息',
          msgType: '9_1'
        },
        {
          typeName: '作业自评消息',
          msgType: '9_6'
        },
        {
          typeName: '考核组间互评消息',
          msgType: '10_1'
        },

        {
          typeName: '作业组间互评消息',
          msgType: '10_6'
        },
        {
          typeName: '考核评价完成消息',
          msgType: '6'
        },
        {
          typeName: '作业评价完成消息',
          msgType: '14'
        },
        {
          typeName: '重考消息',
          msgType: '1'
        },
        {
          typeName: '重做消息',
          msgType: '12'
        },
        {
          typeName: '考核退回消息',
          msgType: '11'
        },
        {
          typeName: '作业退回消息',
          msgType: '13'
        }
      ],
      selfTypeList: [
        {
          typeName: '全部消息类型',
          msgType: ''
        },
        {
          typeName: '问卷消息',
          msgType: '7'
        }
      ],
      noticeTypeList: [
        {
          typeName: '全部消息类型',
          msgType: ''
        },
        {
          typeName: '学校通知',
          msgType: '2'
        },
        {
          typeName: '系统通知',
          msgType: '1'
        }
      ],
      msgList: []
    }
  },
  created() {
    this.getMyMessageList()
    this.myMessageCourseList()
  },
  destroyed() {
  },
  async mounted() {
  },
  watch: {
    navtab() {
      this.keys.indexId = ''
      this.keys.msgType = ''
      this.getMyMessageList()
    }
  },
  methods: {
    async myMessageCourseList() {
      try {
        let res = await myMessageCourseList()
        const { code, data } = res
        if (code == 200) {
          this.courseIndexTree = data
        }
      } catch (e) {
        console.error(e)
      }
    },
    async getMyMessageList() {
      this.loading = true
      this.msgList = []
      try {
        //sort
        let params = {
          type: this.navtab,
          sort: this.keys.sortType,
          indexId: this.keys.indexId?.length ? this.keys.indexId.at(-1) : '',
          readStatus: this.keys.msgStatus,
          pageNum: 1,
          pageSize: 99999
        }
        let res = await getMyMessageList(params)
        const { code, data } = res
        if (code == 200) {
          if (this.navtab == 3) {
            if (data.noticeList.length > 0) {
              data.noticeList.map((item) => {
                item.noticeFiles = JSON.parse(item.noticeFiles)
              })
              if (this.keys.msgType) {
                this.msgList = data.noticeList.filter((row) => {
                  return row.noticeClass == this.keys.msgType
                })
              } else {
                this.msgList = data.noticeList
              }
            }
          } else {
            if (this.keys.msgType || this.keys.msgType == '0') {
              this.msgList = data.messageList.filter((row) => {
                //用于其区分this.keys.msgType 类似8_1 考核和作业的情况
                if (this.keys.msgType.indexOf('_') != -1) {
                  return (
                    row.msgType == this.keys.msgType.split('_')[0] &&
                    row.examType == this.keys.msgType.split('_')[1]
                  )
                } else {
                  return row.msgType == this.keys.msgType
                }
              })
            } else {
              this.msgList = data.messageList
            }
          }
          let unRead = 0
          for (const msgListElement of this.msgList) {
            if (msgListElement.readStatus == 0) {
              unRead++
            }
          }
          this.unread = unRead
          this.courseTypeUnRead = data.unReadCourseMessageNum
          this.selfTypeUnRead = data.unReadPersonalMessageNum
          this.noticeTypeUnRead = data.unReadNoticeNum
          let allUnRead =
            data.unReadCourseMessageNum +
            data.unReadPersonalMessageNum +
            data.unReadNoticeNum
          this.$EventBus.$emit('refresh', allUnRead)
        }
      } catch (e) {
        console.error(e)
      } finally {
        this.loading = false
      }
    },
    //锚点跳转
    scrollToAnchor(item) {
      const anchor = document.getElementById(item.studentId)
      if (anchor) {
        anchor.scrollIntoView({ behavior: 'smooth' })
      }
    },
    openfile(file) {
      window.open(file.url, '_blank')
    },
    // 点击通知消息
    async clickCollapse(e, index) {
      if (e.readStatus == 0) {
        this.noticeTypeUnRead--
        this.msgList[index].readStatus = 1
        await changeReadStatus(e.noticeId)
      }
      this.unread = this.msgList.filter((row) => {
        return row.readStatus == 0
      }).length
      if (this.unread == 0 && this.keys.msgStatus == '0') {
        this.getMyMessageList()
      }
    },
    // 打开问卷
    async answerQuestion(id, markStatus, item, index) {
      await updatePost_readmessage(item.id)
      this.msgList[index].readStatus = 1
      this.$router.push({
        path: '/question',
        query: {
          id: id,
          markStatus: markStatus,
          userId: item.recipientId
        }
      })
    },

    async routeTo(item, index) {
      this.index = index
      this.keyId = item.keyId
      this.msgId = item.id
      this.readStatus = item.readStatus
      if (item.msgType == 8 || item.msgType == 9 || item.msgType == 10) {
        // msgType: 8 --> 考核互评   9 --> 考核自评
        // approvalType  1-师评 2-组长评分(互评) 3-自评 4-组间互评
        let obj = {
          8: '2',
          9: '3',
          10: '4'
        }
        this.$router.push({
          path: '/approvalAnswer',
          query: {
            from: 'msg',
            keyId: item.keyId,
            userId: item.senderId,
            routeSign: 'stu',
            approvalType: obj[item.msgType],
            leaderId: item.remark
          }
        })
      }
      //重考（1）和 退回重做（11）
      //重做（12）和 退回重做（13）
      if (
        item.msgType == 1 ||
        item.msgType == 11 ||
        item.msgType == 12 ||
        item.msgType == 13
      ) {
        let type = item.msgType == 1 || item.msgType == 11 ? 1 : 6
        await updatePost_readmessage(item.id)
        this.$router.push({
          path: '/onlineAssessment',
          query: { id: item.keyId, type: type, studyRecordId: item.remark }
        })
      }
      // 6是考核评价完成 14是作业评价完成
      if (item.msgType == 0 || item.msgType == 6 || item.msgType == 14) {
        await updatePost_readmessage(item.id)
        this.$router.push({
          path: '/examDetail',
          query: { id: item.keyId, examType: item.msgType == 6 ? 1 : 6 }
        })
      }
    },
    intoStorge() {
      this.getMyMessageList()
    },
    changeType(item) {
      this.navtab = item.navtab
    }
  }
}
</script>
<style scoped lang="scss">
.item {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  .label {
    font-size: 14px;
    color: #939393;
  }

  .value {
    width: 300px;
    color: #333333;
    margin-left: 10px;
  }
}

.message {
  ::v-deep .el-collapse-item {
    margin-top: 20px;
  }

  ::v-deep .el-collapse-item__header {
    height: 60px !important;
  }
}

.t {
  height: 60px;
  width: 800px;

  .msgcontent {
    border-bottom: 1px solid #edeff0;
    margin-left: 10px;
    width: 750px;

    .msgName {
      width: 500px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC, sans-serif;
      font-weight: 400;
      color: #333333;
      overflow-wrap: break-word;
      line-height: 20px;

      b {
        word-break: break-all; /* 允许在单词内换行 */
        font-size: 16px;
        font-family: PingFangSC-Semibold, PingFang SC, sans-serif;
        font-weight: 600;
        color: #333333;
        line-height: 16px;
      }
    }

    .unread {
      width: 6px;
      height: 6px;
      background: red;
      top: 13px;
      left: -7px;
      border-radius: 50%;
    }

    .t_t {
      width: 600px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC, sans-serif;
      font-weight: 400;
      color: #999999;
    }

    .t_time {
      padding: 0 5px;
      color: rgba(30, 32, 35, 0.45);
      font-size: 12px;
      font-weight: 400;
    }
  }
}

.t_content {
  padding: 0 10px 10px 10px;
}

.topline {
  padding: 25px 0 22px 36px;
  font-size: 18px;
  font-family: PingFangSC-Semibold, PingFang SC, sans-serif;
  font-weight: 600;
  color: #333333;
  line-height: 25px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #edeff0;

  .clear_all_icon {
    width: 18px;
    height: 18px;
    cursor: pointer;
    user-select: none;
    margin-left: 6px;
  }
}

.types {
  .list {
    .temp {
      width: 240px;
      border-radius: 10px;
      height: 54px;
      margin: 5px auto;
      font-size: 16px;
      color: #333333;
      display: flex;
      align-items: center;
      cursor: pointer;
      user-select: none;
      position: relative;

      .icon {
        margin: 0 17px 0 27px;
        width: 18px;
        height: 18px;
      }

      .tag {
        position: absolute;
        top: 8px;
        right: 8px;
        width: 16px;
        height: 16px;
        background: red;
        border-radius: 50%;
        font-size: 10px;
        color: white;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }

    .active {
      background: #f5faf9 !important;
      color: #28b28b !important;
    }
  }
}

.msg_icon {
  width: 40px;
  height: 40px;
  position: relative;

  .redtip {
    top: 0;
    right: 0;
    width: 8px;
    height: 8px;
    background: #ff3b30;
    border-radius: 4px;
    position: absolute;
  }

  img {
    width: 40px;
    height: 40px;
  }
}

.msg_item {
  width: 100%;
  display: flex;
  align-content: center;
  margin-top: 20px;
  cursor: pointer;
  user-select: none;

  .msgInfo {
    flex: 1;
    padding-left: 16px;
    box-sizing: border-box;

    .flex_bt {
      display: flex;
      justify-content: space-between;
      align-content: center;

      .msgName {
        width: 50%;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC, sans-serif;
        font-weight: 400;
        color: #333333;
        overflow-wrap: break-word;
        line-height: 20px;

        b {
          word-break: break-all; /* 允许在单词内换行 */
          font-size: 16px;
          font-family: PingFangSC-Semibold, PingFang SC, sans-serif;
          font-weight: 600;
          color: #333333;
          line-height: 16px;
        }
      }

      .create_time {
        text-align: right;
        width: 50%;
        padding-top: 5px;
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC, sans-serif;
        font-weight: 400;
        color: #999999;
        line-height: 6px;
      }
    }

    .msgDetail {
      margin-top: 8px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC, sans-serif;
      font-weight: 400;
      color: #999999;
      line-height: 22px;
      border-bottom: 1px solid #edeff0;
      padding-bottom: 4px;
      box-sizing: border-box;
    }
  }
}
</style>
